package com.codeoss.framework.workflow.service.impl;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.workflow.context.WorkflowContext;
import com.codeoss.module.workflow.model.WorkflowActivity;
import com.codeoss.module.workflow.model.WorkflowActivityInstance;
import com.codeoss.module.workflow.model.WorkflowProcess;
import com.codeoss.module.workflow.model.WorkflowToken;
import com.codeoss.module.workflow.service.IWorkflowActivityInstanceService;
import com.codeoss.module.workflow.service.IWorkflowTokenService;

@Service
public class StartNodeService extends AbstractNodeService {
	@Autowired
	private IWorkflowActivityInstanceService workflowActivityInstanceService;
	@Autowired
	private IWorkflowTokenService workflowTokenService;
	@Override
	@Transactional
	public void start(WorkflowContext workflowContext) {
		WorkflowProcess workflowProcess=workflowContext.getWorkflowProcess();
		WorkflowActivity workflowActivity=workflowContext.getWorkflowActivity();
		
		WorkflowActivityInstance workflowActivityInstance=new WorkflowActivityInstance();
		workflowActivityInstance.setWorkflowProcessId(workflowProcess.getId());
		workflowActivityInstance.setWorkflowActivityId(workflowActivity.getId());
		workflowActivityInstance.setStartDate(new Timestamp(System.currentTimeMillis()));
		workflowActivityInstance.setState("DR");
		workflowActivityInstance.setName(workflowActivity.getName());
		workflowActivityInstanceService.insert(workflowActivityInstance);
		
		workflowContext.setWorkflowActivityInstance(workflowActivityInstance);
		
		
		WorkflowToken workflowToken=new WorkflowToken();
		workflowToken.setWorkflowActivityInstanceId(workflowActivityInstance.getId());
		workflowTokenService.insert(workflowToken);
		
		workflowContext.setWorkflowToken(workflowToken);
		
		executeStartExpression(workflowContext);
		
		execute(workflowContext);
	}
}
